﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Teamwish.Domain.Common;
using Teamwish.Domain.Models;

namespace Teamwish.WebUI.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AdminAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool skipAnonymous = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)||filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);
            
            //不跳过处理
            if (!skipAnonymous)
            {
                //从验证票据获取Cookie的名字。
                string cookieName = FormsAuthentication.FormsCookieName;

                //取得Cookie.
                HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[cookieName];

                if (filterContext.HttpContext.Request.Cookies == null ||filterContext.HttpContext.Request.Cookies[cookieName] == null)
                {
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }
               
                //获取凭证
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string[] roles = authTicket.UserData.Split(',');

                //判断用户凭证是否过期
                if (authTicket.Expired)
                {
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }

                //判断用户凭证是否正确
                EfDbContext db = DIFactory.Resolve<EfDbContext>();
                bool isExist = db.Userinfo.Any(p => p.Username == authTicket.Name);
                
                if ((!isExist)&&(authTicket.Name!="Admin"))
                {
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }

                var userIdentity = new GenericIdentity(authTicket.Name);
                var userPrincipal = new GenericPrincipal(userIdentity, roles);

                //设置HttpContext.User
                filterContext.HttpContext.User = userPrincipal;

                base.OnAuthorization(filterContext);
            }
            
           
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            
            filterContext.Result = new RedirectResult("/Admin/Home/Login");
            //filterContext.HttpContext.Response.Redirect("/Admin/Home/Login");//错误的
            //filterContext.HttpContext.Response.End();//无效果，还是会进入action
        }
    }
}